package com.raph.server;

import java.security.SecureRandom;
import java.util.Calendar;
import java.util.TimeZone;

public class UidGenerator {
    private static final String BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static final long EPOCH_MILLIS;

    static {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.set(2020, Calendar.JANUARY, 1, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        EPOCH_MILLIS = calendar.getTimeInMillis();
    }

    public static String generateUID() {
        long currentMillis = System.currentTimeMillis() - EPOCH_MILLIS;
        String timePart = toBase62(currentMillis);
        String randomPart = generateRandomBase62();
        return timePart + randomPart;
    }

    private static String toBase62(long num) {
        StringBuilder sb = new StringBuilder();
        while (num > 0) {
            sb.append(BASE62_CHARS.charAt((int) (num % 62)));
            num /= 62;
        }
        while (sb.length() < 7) {
            sb.append('0');
        }
        return sb.reverse().toString();
    }

    private static String generateRandomBase62() {
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 9; i++) {
            int index = random.nextInt(62);
            sb.append(BASE62_CHARS.charAt(index));
        }
        return sb.toString();
    }
}
